package cn.itsource.interceptor;

import cn.itsource.basic.annotation.PreAuthorize;
import cn.itsource.jwt.*;
import cn.itsource.org.domain.Logininfo;
import cn.itsource.system.mapper.PermissionMapper;
import io.jsonwebtoken.Jwt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PublicKey;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求头中取出token
        String token = request.getHeader("Token");
        String aToken = request.getHeader("Atoken");

        //门户站请求直接放行
        if(aToken != null){
            return true;
        }

        Object loginInfo;
        if(token != null){
            //从redis中查询登录信息
//            loginInfo = redisTemplate.opsForValue().get(token);
            //解密token获取数据
            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa.pub").getFile());
            Payload<PayloadData> payload = JwtUtils.getInfoFromToken(token, publicKey, PayloadData.class);
            //从载荷中获取数据
            PayloadData data = payload.getUserInfo();
            Logininfo logininfo = data.getLogininfo();
            List<String> permissions = data.getPermissions();
            //判断取出的登录信息是否为null
            if(logininfo == null){
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().print(" {\"code\":401,\"success\":false,\"message\":\"未登录\"}");
                return false;
            }
            //查询当前用户的所有permission权限，拥有的permission的sn
//            Logininfo lf = (Logininfo) loginInfo;
//            List<String> permissions = permissionMapper.loadByLoginInfoId(lf.getId());
            //获取当前用户访问的目标方法
            HandlerMethod method = (HandlerMethod) handler;
            //判断目标方法上是否有自定义权限的注解
            PreAuthorize pre = method.getMethodAnnotation(PreAuthorize.class);
            if(pre == null){
                return true;
            }
            //有的话需要判断访问的方法上的sn是否包含在自己拥有的sn
            String methodSn = pre.value();
            if(!permissions.contains(methodSn)){
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().print(" {\"code\":403,\"success\":false,\"message\":\"无权限\"}");
                return false;
            }
        }else {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().print(" {\"code\":401,\"success\":false,\"message\":\"未登录\"}");
            return false;
        }
        //刷新登录过期时间
//        redisTemplate.opsForValue().set(token,loginInfo,30, TimeUnit.MINUTES);
        return true;
    }
}
